﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace SageKing.Core.Extensions;

public static class ClaimsPrincipalExts
{
    public static Dictionary<string, string> ClaimsPrincipalToDictionary(this ClaimsPrincipal principal)
    {
        return principal.Claims
            .GroupBy(c => c.Type) // 处理重复声明（如角色）
            .ToDictionary(
                g => g.Key,
                g => g.Count() > 1 ? string.Join(",", g.Select(c => c.Value)) : g.First().Value
            );
    }
    public static ClaimsPrincipal DictionaryToClaimsPrincipal(this Dictionary<string, string> dic, string name = "CustomAuthentication")
    {
        // 创建声明列表
        var claims = new List<Claim>();
        foreach (var kvp in dic)
        {
            if (kvp.Value.IndexOf(',') > -1)
            {
                var dd = kvp.Value.Split(',');
                foreach (var d in dd)
                {
                    claims.Add(new Claim(kvp.Key, d));
                }
            }
            else
            {

                claims.Add(new Claim(kvp.Key, kvp.Value));
            }
        }
        // 添加一个默认角色声明（如果需要）
        claims.Add(new Claim(ClaimTypes.Role, "Normal")); // 确保使用 ClaimTypes.Role Admin

        // 构建身份标识
        var identity = new ClaimsIdentity(claims, name);

        // 生成 ClaimsPrincipal
        return new ClaimsPrincipal(identity);
    }
    public static string GetUserId(this ClaimsPrincipal User)
    {

        var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
        return userId;
    }

    public static string GetUserName(this ClaimsPrincipal User)
    {
        var userName = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
        return userName;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="User"></param>
    /// <param name="claimTypes">ClaimTypes.xx</param>
    /// <returns></returns>
    public static string GetFirstOrValueByClaimTypes(this ClaimsPrincipal User, string claimTypes)
    {
        var val = User.Claims.FirstOrDefault(c => c.Type == claimTypes)?.Value;
        return val;
    }

    public static bool IsAuthenticated(this ClaimsPrincipal User)
    {
        if (User == null || User.Identity == null)
        {
            return false;
        }
        return User.Identity.IsAuthenticated;
    }
}
